# 抽出session_controller和application_controller的公用方法
module AppMethod
  extend ActiveSupport::Concern

  def error_notice(msg)
    show_js_notice(msg, type: :error)
  end

  def show_js_notice(msg, arg = {})
    if arg[:type].to_s == 'error'
      if msg.is_a?(ApplicationRecord) && msg.errors.values.length>0
        _msg = "操作失败！<br/>#{msg.errors.values.join('<br/>')}"
      end
      render js: "error_notice(#{(_msg||msg).to_json})"
    else
      flash[:notice] = msg
      respond_to do |format|
        format.html { redirect_to request_referer }
        format.js { render js: "Turbolinks.visit(#{(request_referer).to_json})"}
      end
    end
  end


  protected
  def current_user
    if session[:current_user_id].present? && session[:expired_at] && session[:expired_at]>= Time.now
      @current_user ||= Base::User.find(session[:current_user_id]) rescue nil
      cookies.signed[:user_id] ||= @current_user.id rescue nil
      @current_user
    else
      clear_session
    end
  end

  # 引用页
  def request_referer
    request.env['HTTP_REFERER'] || root_path
  end

  def verify_login
    @action_start_time = Time.now
    if current_user.blank?
      session[:login_referer] = request.url
      respond_to do |format|
        format.html { redirect_to login_path }
        format.js { render js: "Turbolinks.visit(#{login_path.to_json})"}
        format.json { render json: {status: :fail, msg: :need_login}}
      end
    else
      session[:expired_at] = Time.now+10.year if Base::Session.rails_test?
      session[:expired_at] = Time.now+2.hours
    end
  end

  def clear_session
    session[:current_user_id] = nil
    session[:current_customer_id] = nil
    session[:expired_at] = nil
    @current_user = nil
  end

  def set_current_user
    if current_user
      Base::Session.set_user current_user
    end
  end


  def load_menu
    @@menus = nil if params[:refresh_menu].to_i==1
    @@menus ||=  YAML.load(IO.read('config/menu.yml'))
    @menus = @@menus
  end

end